package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    GeneratePageService generatePageService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 300000)
    public void publishArticle(Integer newsId) {
        // 1. 根据文章id远程查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        // 2. 基于wmNews封装apArticle
        ApArticle article = getApArticle(wmNews);
        // 3. 保存或修改 article表文章信息
        saveOrUpdateApArticle(article);
        // 4. 保存 关联配置article_config 和 关联详情article_content
        saveConfigAndContent(article,wmNews);
        // 5. 基于文章信息，生成静态页
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        // 6. 远程更新wmNews状态
        updateWmNews(wmNews,article);
        // 7  通知ES索引库更新文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",article.getId());
    }

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        //1 参数检查
        // 页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        dto.setSize(size);
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //2 执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            // 封面在前端不显示，需要我们拼接先路径前缀
            String images = article.getImages();
            // 判断封面是否为空
            if (StringUtils.isNotBlank(images)){
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }
            // 拼接静态页的前缀路径
            article.setStaticUrl(readPath + article.getStaticUrl());
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(articleList);
        return result;
    }

    @Override
    public ResponseResult loadFromCache(Short loadtype, ArticleHomeDTO dto) {
        // 去redis中查询
        String jsonStr = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if(StringUtils.isBlank(jsonStr)){
            // 加载数据库数据
            return load(loadtype,dto);
        }
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
        if (CollectionUtils.isEmpty(hotArticleVoList)){
            // 加载数据库数据
            return load(loadtype,dto);
        }
        for (HotArticleVo articleVo : hotArticleVoList) {
            // 封面在前端不显示，需要我们拼接先路径前缀
            String images = articleVo.getImages();
            // 判断封面是否为空
            if (StringUtils.isNotBlank(images)){
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                articleVo.setImages(images);
            }
            // 静态页 static_url拼接 访问前缀
            articleVo.setStaticUrl(readPath + articleVo.getStaticUrl());
        }
        return ResponseResult.okResult(hotArticleVoList);
    }

    private void updateWmNews(WmNews wmNews,ApArticle article) {
        // 已发布
        wmNews.setStatus(WemediaConstants.WM_NEWS_PUBLISH_STATUS);
        // 设置关联id
        wmNews.setArticleId(article.getId());
        // 远程修改wmNews的状态
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if(!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    /**
     * 保存 配置 和 内容信息
     * @param article
     * @param wmNews
     */
    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        // 保存配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true);
        config.setIsForward(true);
        config.setIsDown(false);
        config.setIsDelete(false);
        apArticleConfigService.save(config);
        // 保存文章详情
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);
    }

    private void saveOrUpdateApArticle(ApArticle article) {
        // 根据文章是否携带id判断 保存 还是 修改
        if(article.getId() == null){
            //    保存
            // 需要补全参数 (点赞量 收藏量 评论量 阅读量)
            article.setLikes(0);
            article.setViews(0);
            article.setComment(0);
            article.setCollection(0);
            this.save(article);
        }else {
            //    修改
            // 根据id修改
            this.updateById(article);
            // 删除关联配置信息
            apArticleConfigService.remove(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,article.getId()));
            // 删除关联详情信息
            apArticleContentService.remove(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,article.getId()));
        }
    }
    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private AuthorMapper authorMapper;

    /**
     * 基于自媒体文章，封装ap_article
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews,article);
        // 设置文章id
        article.setId(wmNews.getArticleId());
        // 设置布局
        article.setLayout(wmNews.getType());
        // 补全频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        AdChannel channel = channelResult.getData();
        article.setChannelName(channel.getName());
        // 补全作者信息
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        return article;
    }

    @Autowired
    private WemediaFeign wemediaFeign;

    /**
     * 根据id使用feign远程查询自媒体文章
     * @param newsId 文章id
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.findWmNewsById(newsId);
        if (!wmNewsResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        // 拿到文章数据
        WmNews wmNews = wmNewsResult.getData();
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short status = wmNews.getStatus();
        if(!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)
                &&
                !WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"自媒体文章状态，不是审核通过状态，发布失败");
        }
        return wmNews;
    }
}